//
//  VideoTableViewController.m
//  LWB_Project
//
//  Created by lanou3g on 15/11/11.
//  Copyright © 2015年 wangjianliang. All rights reserved.
//

#import "VideoTableViewController.h"
#import "VideoTableViewCell.h"
#import "WNetDealTools.h"
#import "DebugNSLog.h"
#import "YyxHeaderRefresh.h"
#import "MJRefresh.h"
#import "MBProgressHUD.h"
#import "DataBasehandle.h"
#define KDataBasehandle [DataBasehandle sharedDataBasehandle]
@interface VideoTableViewController ()<UIScrollViewDelegate>
{
    BOOL isReshing;
    BOOL isLoading;
}
@property (nonatomic, assign) NSInteger currentPage;//当前的页数

@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) UIView  *videoView;

@property (strong, nonatomic) YyxHeaderRefresh *refresh; //下拉刷新

@property (nonatomic,retain) MBProgressHUD * hud;//菊花图标
@property (nonatomic, strong) UIButton  *ControlsmallWindow;

@end
static NSInteger currentSelectIndex = -1;
static VideoTableViewCell *selectCell;
static CGFloat selectposy = 0;;
@implementation VideoTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    [self.tableView registerNib:[UINib nibWithNibName:@"VideoTableViewCell" bundle:nil] forCellReuseIdentifier:@"videocell"];
    //加载图标
    [self p_setupProgressHud];
    //初始化网络下载
    [self loadDatainit];
    //计算窗口的大小 和 ScrollView 的代理方法 用于切换界面
    [self loasWindowAndScrollView];
    
    //下拉刷新 上拉加载
    [self loadrefresh];

}
#pragma mark--- 初始化菊花图标
-(void)p_setupProgressHud{
    
    self.hud = [[MBProgressHUD alloc] initWithFrame:CGRectMake(0,-200,self.view.frame.size.width , self.view.frame.size.height+400)];
    self.hud.minSize = CGSizeMake(100, 100);
    self.hud.mode = MBProgressHUDModeIndeterminate;
    [self.view addSubview:self.hud];
    self.hud.dimBackground = YES;
    self.hud.labelText = @"正在加载数据";
    [self.hud show:NO];
    
}

#pragma mark--- 初始化加载数据
-(void)loadDatainit
{
    
    self.dataArray = [[NSMutableArray alloc] init];
    NSString *NetStates = [[NSUserDefaults standardUserDefaults] objectForKey:@"NETStates"];
    if ([NetStates isEqualToString:@"YES"])
    {
        __weak VideoTableViewController *vc  = self;
        [WNetDealTools GetVideoModelPages:0 Block:^(NSArray *ModelArray)
         {
             [vc.dataArray addObjectsFromArray:ModelArray];
             [vc.tableView reloadData];
             
             if(ModelArray.count == 20)vc.currentPage++;
             
             //菊花停止！
             //加载图标隐藏
             dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                 [vc.hud hide:YES];
             });
             
             //保存数据库中的数据
             [KDataBasehandle createtableName:@"VideoModel" Modelclass:[VideoModel class]];
             for (VideoModel *model in ModelArray) {
                 [KDataBasehandle insertIntoTableModel:model];
             }
             
             
         }];
    }else
    {

        //提示没网
        [self checkNetalerView];
    }


}

#pragma mark--- loadWindowAndScrollView

-(void)loasWindowAndScrollView
{
#pragma mark--- 计算小窗口的高度
    CGFloat windowX = [UIScreen mainScreen].bounds.size.width;
    //CGFloat windowY = [UIScreen mainScreen].bounds.size.height;
    CGFloat windowH = 150 * [UIScreen mainScreen].bounds.size.width/320;
    CGFloat windowW = 150 * [UIScreen mainScreen].bounds.size.width/320;
    UIView *view1 = [[UIView alloc] init];
    //先这样 以后在适配吧
    view1.frame = CGRectMake(windowX - windowH,[UIScreen mainScreen].bounds.size.height -windowH-94, windowW, windowH);
    view1.backgroundColor = [UIColor clearColor];
    view1.userInteractionEnabled = YES;
    _videoView = view1;
    [self.navigationController.view addSubview:view1];
#pragma mark--- 完成ScrollView滑动的代理
    self.tableView.delegate = self;
    //设置上UIcontrol
    self.ControlsmallWindow = [UIButton buttonWithType:UIButtonTypeCustom];
    self.ControlsmallWindow.frame = CGRectMake(_videoView.frame.origin.x, _videoView.frame.origin.y, _videoView.frame.size.width, 30);
    self.ControlsmallWindow.titleLabel.font = [UIFont systemFontOfSize:14];
    [self.ControlsmallWindow setTitle:@"回到播放位置" forState:UIControlStateNormal];
    [self.ControlsmallWindow setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [self.ControlsmallWindow addTarget:self action:@selector(SmallWindowClick:) forControlEvents:UIControlEventTouchDown];
    //self.ControlsmallWindow.backgroundColor = [UIColor redColor];


}

-(void)SmallWindowClick:(UIControl *)sender
{
    MyLog(@"回到播放位置！");
    [self.tableView setContentOffset:CGPointMake(0, selectposy ) animated:YES];
    

}

-(void)loadrefresh
{
    //下拉刷新
    //猫的下拉刷新图标
    self.refresh = [YyxHeaderRefresh header];
    self.refresh.tableView = self.tableView;
    __weak typeof(self) weakSelf = self;
    self.refresh.beginRefreshingBlock = ^(YyxHeaderRefresh *refreshView)
    {
        NSString *NetStates2 = [[NSUserDefaults standardUserDefaults] objectForKey:@"NETStates"];
        if ([NetStates2 isEqualToString:@"YES"])
        {
            //清空
            [weakSelf.dataArray  removeAllObjects];
            [weakSelf.tableView reloadData];
            weakSelf.currentPage = 0;
            
            weakSelf.hud.labelText = @"正在加载数据";
            [weakSelf.hud show:YES];
            //判断网络
            
            //下载
            [WNetDealTools GetVideoModelPages:0 Block:^(NSArray *ModelArray)
             {
                 
                 [weakSelf.dataArray addObjectsFromArray:ModelArray];
                 [weakSelf.tableView reloadData];
                 if (ModelArray.count == 20)
                 {
                     weakSelf.currentPage++;
                 }
                 
                 //菊花停止！
                 //加载图标隐藏
                 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                     [weakSelf.hud hide:YES];
                 });
                 [weakSelf.refresh endRefreshing];
                 
                 
                 //保存数据库中的数据
                 [KDataBasehandle createtableName:@"VideoModel" Modelclass:[VideoModel class]];
                 [KDataBasehandle DeleteTbaleName:@"VideoModel"];
                 for (VideoModel *model in ModelArray) {
                     [KDataBasehandle insertIntoTableModel:model];
                 }

             }];
            
        }
        else
        {
            //提示没网！
            [weakSelf checkNetalerView];
        }
        
    };
    
    //上拉加载
    __block VideoTableViewController *newVC = self;
    //上拉加载:
    [self.tableView addFooterWithCallback:^{
        if (newVC->isReshing)
        {
            return;
        }
        newVC->isLoading = YES;
        
        NSString *NetStates1 = [[NSUserDefaults standardUserDefaults] objectForKey:@"NETStates"];
        if ([NetStates1 isEqualToString:@"YES"])
        {
            newVC.hud.labelText = @"正在加载数据";
            [newVC.hud show:YES];
            
            //判断网络
            //下载
            [WNetDealTools GetVideoModelPages:newVC.currentPage Block:^(NSArray *ModelArray)
             {
                 if (ModelArray.count == 20)
                 {
                     newVC.currentPage++;
                 }
                 [newVC.tableView footerEndRefreshing];
                 [newVC.dataArray addObjectsFromArray:ModelArray];
                 [newVC.tableView reloadData];
                 
                 //菊花停止！
                 //加载图标隐藏
                 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                     [newVC.hud hide:YES];
                 });
                 [newVC.tableView footerEndRefreshing];
                 
                 
                 //保存数据库中的数据
                 [KDataBasehandle createtableName:@"VideoModel" Modelclass:[VideoModel class]];
                 for (VideoModel *model in ModelArray) {
                     [KDataBasehandle insertIntoTableModel:model];
                 }
                 
             }];
        }else
        {
            //提示没网！
            [newVC checkNetalerView];
        }
        
        newVC->isLoading = NO;
        
    }];
}


-(void)checkNetalerView
{

    //数据库中读出来！！！！
    [KDataBasehandle createtableName:@"VideoModel" Modelclass:[VideoModel class]];
    self.dataArray = [KDataBasehandle selectAllModel];
    [self.tableView reloadData];
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请检查网络连接" preferredStyle:(UIAlertControllerStyleAlert)];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确认" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:action];
    [self presentViewController:alert animated:YES completion:nil];
    
    [self.hud hide:YES];
    [self.refresh endRefreshing];
    [self.tableView footerEndRefreshing];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80 + 180 *  [UIScreen mainScreen].bounds.size.width/320;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    
    VideoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"videocell" forIndexPath:indexPath];
    
    //必须先传递这些信息
    cell.index = indexPath.row;
    cell.superView = self.videoView;
    cell.model = self.dataArray[indexPath.row];
    cell.selectedBackgroundView = [[UIView alloc] initWithFrame:cell.bounds];
    
    #pragma mark--- 这里很重要 返回当前的播放视频Cell!
    if (currentSelectIndex == indexPath.row) {
        selectCell = cell;
    }
    
    //记录当前播放的currentSelectIndex
    cell.blockIndex = ^(NSInteger selectIndex)
    {
        currentSelectIndex = selectIndex;
         //返回当前的播放视频Cell!
        selectCell = cell;
        selectposy = self.tableView.contentOffset.y;
        if (self.ControlsmallWindow.superview)
        {
            [self.ControlsmallWindow removeFromSuperview];
        }
    };
    return cell;
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    MyLog(@"正在滚动中");
    static CGFloat cellHeight ;
    static CGFloat ScreenHeight ;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^
    {
        cellHeight =  80 + 180 *  [UIScreen mainScreen].bounds.size.width/320;
        ScreenHeight = [UIScreen mainScreen].bounds.size.height;
    });
    
    #pragma mark--- 当前的Cell视频播放位置判断是不是在窗口上
    //distance 一般情况下是 正数
    CGFloat distance = scrollView.contentOffset.y;

        
        //这时说明 向上拉的时候 cell的视频播放窗口 已经移除了屏幕上
        //这时候 应该切换成小窗口 distance 越来越大 cell 不在屏幕上了！
        if ( distance -  ((currentSelectIndex+1) * cellHeight) + 80 + 64  > 0) {
          
            if (currentSelectIndex != -1)
            {

                
                if (self.ControlsmallWindow.superview == nil)
                {
                    if([VideoTableViewCell GetplayerStates])
                    [self.navigationController.view addSubview: self.ControlsmallWindow];
                }
                [selectCell switchVideoWindow:1];
                //在不播放的时候 不添加这个就行了
                if([VideoTableViewCell GetplayerStates])
                [self.navigationController.view bringSubviewToFront:self.ControlsmallWindow];
            }

        }
        //这时候 说明向下拉 distance 距离越来越小  说明cell不在屏幕上了
        if ( ( (currentSelectIndex *cellHeight -ScreenHeight) - distance + 64) >0 )
        {
            
            if (currentSelectIndex != -1)
            {
                [selectCell switchVideoWindow:1];

                if (self.ControlsmallWindow.superview == nil)
                {
                    if([VideoTableViewCell GetplayerStates])
                    [self.navigationController.view addSubview: self.ControlsmallWindow];
                }
                //在不播放的时候 不添加这个就行了
                if([VideoTableViewCell GetplayerStates])
                [self.navigationController.view bringSubviewToFront:self.ControlsmallWindow];
            }
        }
    
        //如果回到了这个界面那就切换到 当前的cell上显示视频！
        if ( distance -  ((currentSelectIndex+1) * cellHeight) + 80 + 64  < 0)
        if ( ( (currentSelectIndex *cellHeight -ScreenHeight) - distance + 64) <0 )
        {
            if (currentSelectIndex != -1)
            {
                if (self.ControlsmallWindow.superview)
                {
                  [self.ControlsmallWindow removeFromSuperview];
                }
                [selectCell switchVideoWindow:0];
            }

        
        }
    
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Table view delegate

// In a xib-based application, navigation from a table can be handled in -tableView:didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here, for example:
    // Create the next view controller.
    <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:<#@"Nib name"#> bundle:nil];
    
    // Pass the selected object to the new view controller.
    
    // Push the view controller.
    [self.navigationController pushViewController:detailViewController animated:YES];
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
